package com.yxhl.zoume.core.user.ui.fragment;

import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yxhl.zoume.R;
import com.yxhl.zoume.account.event.UserLoginEvent;
import com.yxhl.zoume.account.event.UserLogoutEvent;
import com.yxhl.zoume.common.ui.fragment.BaseFragment;
import com.yxhl.zoume.common.ui.view.MobileDialView;
import com.yxhl.zoume.core.main.ui.MainActivity;
import com.yxhl.zoume.core.user.presenter.UserCenterPresenter;
import com.yxhl.zoume.core.user.ui.info.UserCenterPageEnum;
import com.yxhl.zoume.core.user.view.UserCenterHomeView;
import com.yxhl.zoume.data.http.model.account.ZMAccount;
import com.yxhl.zoume.di.component.usercenter.DaggerUserCenterComponent;
import com.yxhl.zoume.di.component.usercenter.UserCenterComponent;
import com.yxhl.zoume.di.module.ActivityModule;
import com.yxhl.zoume.di.module.usercenter.UserCenterModule;
import com.yxhl.zoume.utils.AccountUtils;
import com.yxhl.zoume.utils.DeviceUtils;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.StringUtils;
import com.yxhl.zoume.utils.permission.PermissionHelper;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * 我的
 * Created by Xboy on 16/3/11.
 */
public class UserHomeFragment extends BaseFragment implements MobileDialView, UserCenterHomeView {

    public static final int LOGOUT_STATUS = 1;
    public static final int LOGIN_STATUS = 2;
    private static final String TAG = "UserHomeFragment";
    /**
     * 登录
     */
    @BindView(R.id.ll_login_logout)
    public LinearLayout mLoginLogoutLayout;
    @BindView(R.id.tv_mobile_phone_status)
    public TextView mMobilePhoneTextView;
    @BindView(R.id.iv_right_arrow)
    public ImageView mRightArrowIv;
    /**
     * 乘客管理
     */
    @BindView(R.id.rl_passengers_mgmt)
    public RelativeLayout mPassengersMgmtLayout;

    /**
     * 帮助中心
     */
    @BindView(R.id.rl_help_center)
    public RelativeLayout mHelpCenterLayout;

    /**
     * 服务热线
     */
    @BindView(R.id.rl_service_hotline)
    public RelativeLayout mServiceHotLineLayout;
    @BindView(R.id.hotline_textview)
    public TextView mobileView;
    @Inject
    public UserCenterPresenter mUserCenterPresenter;
    /**
     * 实名认证
     */
    @BindView(R.id.rl_name_identification_container)
    RelativeLayout mIdentificationRl;
    private Dialog mLogoutDialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        LOG.e(TAG, "onCreateView");
        View view = super.onCreateView(inflater, container, savedInstanceState);
        mUserCenterPresenter.attachView(this);
        initializeShow();
        onRxBusEvent();
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        LOG.e(TAG, "onResume");
        mUserCenterPresenter.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        LOG.e(TAG, "onPause");
        mUserCenterPresenter.onPause();
    }


    @Override
    public void onDestroyView() {
        LOG.e(TAG, "onDestroyView");
        getSubscription().unsubscribe();
        mSubscription = null;
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        LOG.e(TAG, "onDestroy");
        if (mLogoutDialog != null) {
            if (mLogoutDialog.isShowing()) {
                mLogoutDialog.dismiss();
            }
        }
        mUserCenterPresenter.onDestroy();
        super.onDestroy();
    }

    public void initializeShow() {
        ZMAccount account = AccountUtils.getInstance(getContext()).getAccount();
        LOG.e(TAG, "account = " + account);
        if (account != null) {
            String accessToken = account.getAccessToken();
            if (!TextUtils.isEmpty(accessToken)) {
                String accountName = account.getAccountName();
                setLoginStatus(accountName);
            } else {
                setLogoutStatus();
            }
        } else {
            setLogoutStatus();
        }
    }

    @OnClick({R.id.rl_passengers_mgmt})
    public void onPassengerMgmtClick(View view) {
        if (null != view) {
            int viewId = view.getId();
            switch (viewId) {
                case R.id.rl_passengers_mgmt:
                    navigateToPassengerManager();
                    break;
            }
        }
    }

    /**
     * 登录点击事件
     */
    @OnClick(R.id.ll_login_logout)
    public void onLoginClick(View view) {
        String account = AccountUtils.getInstance(mActivity).getAccount().getAccountName();
        if (StringUtils.isNullOrEmpty(account)) {
            getAppComponent().navigator().navigateToMobileLogin(mActivity);
            LOG.v(TAG, "account == null  "+account);
        } else {
            LOG.v(TAG, "account != null  " + account);
        }
    }

    public void onRxBusEvent() {
        getSubscription().add(toSubscription(UserLoginEvent.class,
                new Action1<UserLoginEvent>() {
                    @Override
                    public void call(UserLoginEvent userLoginEvent) {
                        ZMAccount account = AccountUtils.getInstance(getContext()).getAccount();
                        if (account != null) {
                            String accountName = account.getAccountName();
                            setLoginStatus(accountName);
                        }
                    }
                }
        ));
        getSubscription().add(toSubscription(UserLogoutEvent.class,
                new Action1<UserLogoutEvent>() {
                    @Override
                    public void call(UserLogoutEvent userLogoutEvent) {
                        setLogoutStatus();
                    }
                }
        ));
    }

    /**
     * 跳转到乘客管理界面
     */
    private void navigateToPassengerManager() {
        getAppComponent().navigator().
                navigateToPassengerManagement(getActivity(), UserCenterPageEnum.PASSENGER_MANAGEMENT);
    }

    /**
     * 帮助中心点击事件
     */
    @OnClick(R.id.rl_help_center)
    public void onHelpCenterClick(View view) {
        getAppComponent().navigator().navigateToHelpCenter(mActivity, UserCenterPageEnum.HELP_CENTER);
    }

    /**
     * 服务热线点击事件
     */
    @OnClick(R.id.rl_service_hotline)
    public void onServiceHotLineClick(View view) {
        if (PermissionHelper.checkPhonePermission(mActivity)) {
            dial();
        } else {
            PermissionHelper.takeCallPhonePermission(mActivity, PermissionHelper.REQUEST_CODE_CALL_USER_CENTER);
        }
    }

    /**
     * 实名认证
     */
    @OnClick(R.id.rl_name_identification_container)
    public void onIdentificationClick() {
        getAppComponent().navigator().navigateToNameIdentification(mActivity);
    }

    /**
     * 优惠券点击事件
     */
    @OnClick(R.id.rl_coupon)
    public void onCouponClick() {
        getAppComponent().navigator().navigateToCoupon(mActivity);
    }

    /**
     * 钱包  反馈  更多
     *
     * @param view
     */
    @OnClick({R.id.rl_wallet, R.id.rl_feedback, R.id.rl_more})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_wallet:
                getAppComponent().navigator().navigateToMyWallet(mActivity);
                break;
            case R.id.rl_feedback:
                getAppComponent().navigator().navigateToFeedback(mActivity, UserCenterPageEnum.FEEDBACK);
                break;
            case R.id.rl_more:
                getAppComponent().navigator().navigateToMore(mActivity, UserCenterPageEnum.MORE);
                break;
        }
    }


    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_user_home;
    }

    @Override
    protected void setupToolBar() {
        ((MainActivity) mActivity).setToolbarTitle(getString(R.string.main_tab_name_mine));
        ((MainActivity) mActivity).setToolbarVisible(false);
    }

    /**
     * 拨打电话
     */
    @Override
    public void dial() {
        String telNum = mobileView.getText().toString().trim();
        DeviceUtils.dialTelPhone(mActivity, telNum);
    }

    @Override
    public void logoutResult() {
        //清空登录Token
        AccountUtils.getInstance(mActivity).saveAccount(new ZMAccount("", ""));

        //更新UI
        setLogoutStatus();

        //关闭对话框
        if (mLogoutDialog != null) {
            if (mLogoutDialog.isShowing()) {
                mLogoutDialog.dismiss();
            }
        }
    }

    private void setLoginStatus(String accountName) {
        mRightArrowIv.setVisibility(View.INVISIBLE);
        mLoginLogoutLayout.setClickable(false);
        mMobilePhoneTextView.setText(StringUtils.getFilteredAccountName(accountName));
    }

    private void setLogoutStatus() {
        //销毁本地保存数据
        AccountUtils.getInstance(getContext()).saveAccount(new ZMAccount());
        if (mRightArrowIv != null) {
            mRightArrowIv.setVisibility(View.VISIBLE);
        }
        mLoginLogoutLayout.setClickable(true);
        mMobilePhoneTextView.setText(R.string.user_center_logout_title);
    }

    @Override
    protected void initializeInjector() {
        UserCenterComponent userCenterComponent = DaggerUserCenterComponent.builder()
                .appComponent(getAppComponent())
                .activityModule(new ActivityModule(mActivity))
                .userCenterModule(new UserCenterModule())
                .build();
        userCenterComponent.inject(this);
    }

}
